import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'logic.dart';

class ClearEditText extends StatelessWidget {
  final logic = Get.put(EditTextLogic());
  String _editText = "";
  String _hint;
  TextInputType type; //主要控制输入值的类型，跳出键盘
  final ValueChanged<String> _onChanged; //方法，监听值
  VoidCallback? _onSubmited; //方法，监听值
  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();
  bool isScan;
  bool isShowIcon;

  ClearEditText(this._hint, this._onChanged,
      {this.type = TextInputType.text,
        VoidCallback? onSubmited,
      FocusNode? focusNode,
      TextEditingController? controller,
      this.isScan = true,
      this.isShowIcon = true}) {
    if (focusNode != null) {
      this.focusNode = focusNode;
    }
    if (controller != null) {
      this.controller = controller;
    }
    if(onSubmited != null){
      this._onSubmited = onSubmited;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<EditTextLogic>(
        builder: (logic) => Container(
              height: 40,
              padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
              margin: EdgeInsets.only(top: 1),
              color: Colors.white,
              child: TextField(
                controller: controller,
                focusNode: focusNode,
                keyboardType: type,
                onSubmitted: (value) {
                  _onChanged(value);
                },
                decoration: InputDecoration(
                    border: new UnderlineInputBorder(
                        borderSide: new BorderSide(color: Colors.red)),
                    hintText: '$_hint',
                    hintStyle: TextStyle(
                      fontSize: 14,
                    ),
                    //文本框的尾部图标
                    suffixIcon: controller.text.length > 0 && isShowIcon
                        ? IconButton(
                            //如果文本长度不为空则显示清除按钮
                            onPressed: () {
                              controller.text = "";
                              _editText = "";
                              logic.update();
                            },
                            icon: Icon(Icons.cancel, color: Colors.grey))
                        : null),
                onChanged: (value) {
                  if (isScan) {
                    if (_editText.length == 0 && value.length > 1) {
                      _onChanged(value);
                    }
                  } else {
                    _onChanged(value);
                  }
                  _editText = value.toString();
                  // logic.update();
                },
                onEditingComplete:  _onSubmited,
              ),
            ));
  }
}
